<?php

class ComManagerUnkownComponentError extends Exception {}
class ComManager
{
	public function create ($n, $arg)
	{
		global $rh;
		if (isset($rh->ctx->$n)) return $rh->ctx->$n;
		throw new ComManagerUnkownComponentError($n);
	} // end of method create

	static $namespace = 'ComManager.';

	/**
	 * Реализует логику get or create.
	 */
	static public function get ($name)
	{
		$com = Registry::get(self::getFullName($name));
		if ($com === NULL) {
			$com = self::instance()->create($name, $args);
			self::set($name, $com);
		}
		return $com;
	} // end of method get

	static private function set ($name, $com)
	{
		return Registry::set(self::getFullName($name), $com);
	} // end of method get
	static private function instance ()
	{
		$factory = Registry::get('ComManager', false);
		if ($factory === false) {
			$factory = new ComManager();
			Registry::set('ComManager', $factory);
		}
		return $factory;
	} // end of method instance
	static private function getFullName ($name)
	{
		return self::$namespace . $name;
	} // end of method getFullName
}

class Registry
{
	var $stack = array(array());
	static $instance;

	public function &getParam ($n, $default=NULL)
	{
		if (array_key_exists($n, $this->stack[0])) return $this->stack[0][$n];
		return $default;
	} // end of method getParam
	public function setParam ($n, $v)
	{
		$this->stack[0][$n] = $v;
		return $this;
	} // end of method setParam
	public function push ($clone)
	{
		array_unshift($this->stack, $clone ? $this->stack[0] : array());
		return $this;
	} // end of method push
	public function pop ()
	{
		array_shift($this->stack);
		return $this;
	} // end of method pop

	static public function set ($n, $v)
	{
		return self::instance()->setParam($n, $v);
	} // end of method set
	static public function &get ($n, $default=NULL)
	{
		return self::instance()->getParam($n, $default);
	} // end of method set
	static public function save ($clone=true)
	{
		return self::instance()->push($clone);
	} // end of method save
	static public function restore ()
	{
		return self::instance()->pop();
	} // end of method save

	static private function instance ()
	{
		if (!isset(self::$instance)) self::$instance = new Registry();
		return self::$instance;
	} // end of method instance
}

class Pager
{
	var $query;
	var $length;
	var $rq = 'p';

	var $handler;
	var $store;

	var $alias='page';
	var $first = 1;
	var $default = 1;

	public function initalize ($env)
	{
		foreach ($env as $k=>$v) $this->$k = $v;
	} // end of method initalize

	public function getSQL ()
	{
		$ql = clone $this->query;
		$sql = $ql->setPage($this->getPage(), $this->length)->getSQL();
		return $sql;
	} // end of method getSQL
	public function getInfo ()
	{
		$handler = $this->handler;
		$rq = $this->rq;
		$length = $this->length;
		$store = $this->store;
		$first_page = $this->first;
		$default_page = $this->default;

		$page = $this->getPage();
		$items = $this->getCount();

		$pager = array();

		$last_page = (int)ceil($items / $length);

		$pager['first'] = $first_page;
		$pager[ 'last'] = $last_page;
		$pager['count'] = $items;
		$pager[ 'page'] = $page;
		$pager[ 'prev'] = ($page > $last_page ? $last_page : 
		                  ($page > 1          ? $page - 1 : NULL));
		$pager[ 'next'] = ($page < 1          ? $first_page : 
			                ($page < $last_page ? $page + 1 : NULL));

		$handler->rh->UseClass("RL_URLGenerator");
		$ug = new RL_URLGenerator($handler->rh->router->getLastMatched());
		$ug->setRouter($handler->rh->router);
		$ug->setParams($handler->params);

		// урл для постраничной листалки без ajax

		if (isset($pager['prev'])) {
			$ug->setGet(array_merge($handler->rh->GET, array($rq=>$pager['prev'] == $default_page ? NULL : $pager['prev'])));
			$pager['prev_url'] = $ug->generateUrl();
		}
		if (isset($pager['next'])) {
			$ug->setGet(array_merge($handler->rh->GET, array($rq=>$pager['next'] == $default_page ? NULL : $pager['next'])));
			$pager['next_url'] = $ug->generateUrl();
		}

		return $pager;
	} // end of method getInfo

	public function getPage ()
	{
		$rq = $this->rq;
		$handler = $this->handler;
		$default_page = $this->default;

		return isset($handler->rh->GET[$rq]) ? $handler->rh->GET[$rq] : $default_page;
	} // end of method getPage
	public function getCount ()
	{
		$store = $this->store;
		$alias = $this->alias;

		$row = $store->query($this->getLastPageSQL())->next();
		return $row[$alias];
	} // end of method getItemCount

	private function getLastPageSQL ()
	{
		$alias = $this->alias;
		$query = $this->query; 

		$ql = clone $query;
		$sql = $ql->setCount($alias)->getSQL();
		return $sql;
	} // end of method getLastPageNo
}


// ### AclAssistant : Community
class Action_Node_ShowAllCommunities extends RL_Handler
{
	var $template_data = array();
	
	private function toTemplate(array $to_add) {
		$this->template_data = array_merge($to_add, $this->template_data);
	}
	
	public function init() {
		$this->rh->UseClass('RL_CyrDate');
		$this->acla = $this->module->aa;
		$this->acld = $this->acla->getInfo();
		$this->acla->getAvailableOperations();
		$this->store = ComManager::get('store');
	}
	
	private function getCommunities() {
		$store = ComManager::get('store');

		$ql = new QLSelectQuery("objects where objects.type = :type and objects.is_deleted=0 order by objects.ctime desc");
		$ql->initalize(array('compiler'=>$store->qlc)); 
		$ql->setParam('type','fcommunity');

		$pager = new Pager();
		$pager->initalize(array('query' => $ql, 'length'=>20, 'rq'=>'p', 'handler'=>$this, 'store' => $store));

		$rs = $store->findSQL($pager->getSQL());
		if ($rs)
		while ($obj = $rs->next()) {
			$items[] = array_merge($obj->data, array(
				'ctime' => RL_CyrDate::newFromStr("%Y-%m-%d %H:%i:%s", $obj->ctime),
				'oid' => $obj->id
			)); 
		}

		return array(
				"communities"=>$items,
				'pager' => $pager->getInfo(),
				);
	}
	
	public function process ()
	{
		$this->toTemplate( $this->acla->template_data );
		$this->toTemplate( $this->getCommunities() );
		
		// set view
		$view = $this->rh->views->findByName('all_communities');
		$view->data = $this->template_data;
		
		$view->data['is_allcommunities'] = true;
		
		$this->rh->response->setContent( $view );
	} // end of function execute

}
